package org.example.order.controller;

import jakarta.annotation.Resource;
import org.example.order.common.APIResponse;
import org.example.order.common.ResponseCode;
import org.example.order.permission.Access;
import org.example.order.permission.AccessLevel;
import org.example.order.service.CoverFileService;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.file.Files;

@RestController
@RequestMapping("/cover")
public class CoverFileController {
    @Resource
    private CoverFileService coverFileService;

    @Access(level = AccessLevel.ADMIN)
    @PostMapping("/upload")
    public APIResponse<String> upload(@RequestParam("cover") MultipartFile file) {
        try {
            String fileName = coverFileService.upload(file);
            return new APIResponse<>(ResponseCode.SUCCESS, fileName);
        } catch (Exception e) {
            return new APIResponse<>(ResponseCode.INTERNAL_SERVER_ERROR, e.getMessage());
        }
    }

    @GetMapping("/{fileName}")
    public ResponseEntity<byte[]> getCover(@PathVariable("fileName") String fileName) {
        String path = System.getProperty("user.dir") + "/src/main/resources/upload/cover/" + fileName;
        String coverType = fileName.substring(fileName.lastIndexOf(".") + 1);
        File imageFile = new File(path);
        try {
            byte[] imageBytes = Files.readAllBytes(imageFile.toPath());

            HttpHeaders headers = new HttpHeaders();
            if (coverType.equalsIgnoreCase("jpg")) {
                headers.setContentType(MediaType.IMAGE_JPEG);
            } else if (coverType.equalsIgnoreCase("png")) {
                headers.setContentType(MediaType.IMAGE_PNG);
            }
            headers.setContentLength(imageBytes.length);

            return new ResponseEntity<>(imageBytes, headers, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }
}
